package com.jk.tweetsnear.fragment;

import twitter4j.GeoLocation;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.jk.tweetsnear.MainActivity;
import com.jk.tweetsnear.R;
import com.jk.tweetsnear.application.App;
import com.jk.tweetsnear.data.TweetData;
import com.jk.tweetsnear.list.adapter.TweetListBaseAdapter;
import com.jk.tweetsnear.pulltorefresh.RefreshableListView;
import com.jk.tweetsnear.pulltorefresh.RefreshableListView.OnRefreshListener;
import com.jk.tweetsnear.utils.Const;
import com.jk.tweetsnear.utils.Utils;

public class TweetListFragment extends Fragment
{
	public final String TAG = getClass().getSimpleName() + Utils.TAG_OPTION;

	private RefreshableListView listView;
	private TweetListBaseAdapter tweetListBaseAdapter;
	private ProgressDialog progDialog;
	private AsyncGetGeo getGeo;
	private Tracker mGaTracker;
	private GoogleAnalytics mGaInstance;	

	public int itemNum;
	public int totalListNum;
	
	private final int ALREADY_FOLLOWING = 10;
	private final int FOLLOWING = 11;
	private final int LIST_NOTI =12;

	@Override
	public void onStart()
	{
		super.onStart();
		mGaTracker.sendView("/TweetListFragment");
	}	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.tweet_list_fragment, null);
		
		mGaInstance = GoogleAnalytics.getInstance(App.act);
		mGaTracker = mGaInstance.getTracker(Utils.TRACKER_ID); 		
		
		setWidjet(view);

		if (MainActivity.arrayTweetData.size() == 0)
		{
			Utils.getCurrentLocation(App.act);

			getGeo = new AsyncGetGeo();
			getGeo.execute();
		}

		return view;
	}

	private class AsyncGetGeo extends AsyncTask<Void, Void, Void>
	{
		private TweetData data;

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			if (progDialog == null)
			{
				progDialog = new ProgressDialog(App.act);
			}
			progDialog.setMessage("please wait...");
			progDialog.setCancelable(false);
			progDialog.show();
			
			Utils.getCurrentLocation(App.act);
		}

		protected Void doInBackground(Void... params)
		{
			
			int i = 0;
			
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(Const.CONSUMER_KEY);
			builder.setOAuthConsumerSecret(Const.CONSUMER_SECRET);

			String access_token = App.sharedPreferences.getString(Const.PREF_KEY_OAUTH_TOKEN, "");
			String access_token_secret = App.sharedPreferences.getString(Const.PREF_KEY_OAUTH_SECRET, "");

			AccessToken accessToken = new AccessToken(access_token, access_token_secret);
			App.twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

			Query query = new Query();
			query.count(50);
			query.setGeoCode(new GeoLocation(App.currentLat, App.currentLon), 1, Query.KILOMETERS);

			QueryResult result = null;

			try
			{
				result = App.twitter.search(query);
			} catch (TwitterException e1)
			{
				e1.printStackTrace();
			}

			if (Utils.DEBUG)
				Log.e(Utils.FILLTER, TAG + " tweet count : " + result.getCount());
			
			do
			{
				if (result.getCount() != 0)
				{

					for (twitter4j.Status status : result.getTweets())
					{

						if (i == MainActivity.TWEET_COUNT)
							break;

						if (status.getGeoLocation() != null)
						{
							data = new TweetData();

							if (Utils.DEBUG)
							{
								Log.i(Utils.FILLTER, "===============================================================");
								Log.i(Utils.FILLTER, TAG + " @" + status.getUser().getScreenName() + ":" + status.getText());
								Log.i(Utils.FILLTER, TAG + " lon : " + status.getGeoLocation().getLongitude() + ", lat : " + status.getGeoLocation().getLatitude());
								Log.i(Utils.FILLTER, TAG + " name : " + status.getUser().getName());
								Log.i(Utils.FILLTER, TAG + " profileImageUrl : " + status.getUser().getOriginalProfileImageURL());
								Log.i(Utils.FILLTER, TAG + " create time : " + status.getCreatedAt().toString());
							}

							data.setLat(status.getGeoLocation().getLatitude());
							data.setLon(status.getGeoLocation().getLongitude());
							data.setName(status.getUser().getName());
							data.setScreenName(status.getUser().getScreenName());
							data.setText(status.getText());
							data.setProfileUrl(status.getUser().getProfileImageURL());
							data.setCreateTime(Utils.compateCreatedAt(status));

							MainActivity.arrayTweetData.add(i, data);

							i++;
						}
					}

					break;

				} else
				{
					if (Utils.DEBUG)
						Log.i(Utils.FILLTER, TAG + "tweets location is 0...");
				}

			} while ((query = result.nextQuery()) != null);

			if (Utils.DEBUG)
				Log.e(Utils.FILLTER, TAG + "tweet size = " + MainActivity.arrayTweetData.size());

			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			Message msg = new Message();
			msg.what = LIST_NOTI;
			handler.sendMessage(msg);			
			
			progDialog.dismiss();

			if (Utils.DEBUG)
				Log.i(Utils.FILLTER, TAG + "onPostExecute...");

			super.onPostExecute(result);
		}
	}

	private void setWidjet(View view)
	{
		listView = (RefreshableListView) view.findViewById(R.id.list_live);
		tweetListBaseAdapter = new TweetListBaseAdapter(App.act, R.layout.row_tweet_list_listview);
		listView.setAdapter(tweetListBaseAdapter);
		
		listView.setOnItemClickListener(onItemClick);
		listView.setOnRefreshListener(onRefresh);

	}
	
	OnRefreshListener onRefresh = new OnRefreshListener()
	{
		
		@Override
		public void onRefresh(RefreshableListView listView)
		{
			MainActivity.arrayTweetData.clear();		
			tweetListBaseAdapter.notifyDataSetChanged();
			
			mGaTracker.sendEvent("ui_action", "listview_controll", "listview_refresh", 0L);			
			
			getGeo = new AsyncGetGeo();
			getGeo.execute();		
		}
	};

	OnItemClickListener onItemClick = new OnItemClickListener()
	{

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
		{
			mGaTracker.sendEvent("ui_action", "button_press", "twitter_listview_item", 0L);			
			
			new AsyncWaiting().execute(position);
		}

	};
	
	@Override
	public void onResume()
	{
		super.onResume();
		if (Utils.DEBUG)
			Log.v(Utils.FILLTER, TAG + "onResume...");
	}
	
	Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			String targetScreenName = (String) msg.obj;
			
			switch (msg.what)
			{
			case ALREADY_FOLLOWING:
				mGaTracker.sendEvent("ui_action", "button_press", "twitter_already_following", 0L);
				
				Utils.showAlreadyFollowingAlert(App.act, targetScreenName);
				break;
			case FOLLOWING:
				mGaTracker.sendEvent("ui_action", "button_press", "twitter_following", 0L);
				
				Utils.showFollowingAlert(App.act, targetScreenName);
				break;
			case LIST_NOTI:
				listView.completeRefreshing();
				tweetListBaseAdapter.notifyDataSetChanged();
				
				if(MainActivity.arrayTweetData.size() == 0)
					Toast.makeText(App.act, "sorry no tweets..", Toast.LENGTH_LONG).show();
				
				break;
			}
			
			super.handleMessage(msg);
		}
	};

    private class AsyncWaiting extends AsyncTask<Integer, Void, Void> {

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			if (progDialog == null)
			{
				progDialog = new ProgressDialog(App.act);
			}
			progDialog.setMessage("please wait...");
			progDialog.setCancelable(false);
			progDialog.show();
			
			Utils.getCurrentLocation(App.act);
		}
    	
        @Override
        protected Void doInBackground(Integer... position) {
			if(App.twitter != null)
			{
				try
				{
					String targetScreenName = MainActivity.arrayTweetData.get(position[0]).getScreenName();
					boolean isFollowing = App.twitter.showFriendship(App.twitter.getScreenName(), targetScreenName).isSourceFollowingTarget();
					
					if(isFollowing)
					{
						Message msg = new Message();
						msg.what = ALREADY_FOLLOWING;
						msg.obj = targetScreenName;
						handler.sendMessage(msg);
					} else 
					{
						Message msg = new Message();
						msg.what = FOLLOWING;
						msg.obj = targetScreenName;
						handler.sendMessage(msg);						
					}
					
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
        	
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

        	progDialog.dismiss();
        	
            super.onPostExecute(result);
        }
    }
}